package com.way.demo.listener;

import com.way.demo.comm.UserInfoContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.http.HttpServletRequest;

/**
 * @author lipingwei
 * @create 2021-05-12 15:39
 * desc: listener 监听request  用于释放线程绑定的用户信息，避免内存泄露
 */
@Component
@Slf4j
public class RequestListener implements ServletRequestListener {

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        //request  初始化
        HttpServletRequest request  = (HttpServletRequest) sre.getServletRequest();
        log.info("当前线程 --- [{}] --- 创建请求：{}", Thread.currentThread().getName() ,request.getRequestURI());
    }

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request  = (HttpServletRequest) sre.getServletRequest();
        log.info("当前线程 --- [{}] --- 销毁请求：{}", Thread.currentThread().getName() , request.getRequestURI());
        UserInfoContextHolder.removeToken();
        UserInfoContextHolder.removeUserInfo();
    }
}
